package com.kly.smartbi.manager;

import com.kly.smartbi.config.CosClientConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.LinkedList;
import java.util.List;

/**
 * Cos 对象存储操作
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@Component
public class CosManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private COSClient cosClient;


    /**
     * 返回对象的 URL
     */
    public String getObjectUrl(String uploadPath) {
        // https://smart-bi-1329071127.cos.ap-chengdu.myqcloud.com/
        // public/2025/04/08/ec5bf0b6-4e86-4222-a974-11146e6d2c34.png
        return String.format("https://%s.cos.%s.myqcloud.com/%s",
                cosClientConfig.getBucket(),
                cosClientConfig.getRegion(),
                uploadPath);
    }

    /**
     * 上传对象
     *
     * @param key 唯一键
     * @param localFilePath 本地文件路径
     * @return
     */
    public PutObjectResult putObject(String key, String localFilePath) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key,
                new File(localFilePath));
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 上传对象
     *
     * @param key 唯一键
     * @param file 文件
     * @return
     */
    public PutObjectResult putObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key,
                file);
        PicOperations picOperations = new PicOperations();
        picOperations.setIsPicInfo(1);
        // 添加图片处理规则
        List<PicOperations.Rule> ruleList = new LinkedList<>();
        PicOperations.Rule rule1 = new PicOperations.Rule();
        rule1.setBucket(cosClientConfig.getBucket());
        // 获取文件名
        String fileName = key.substring(key.lastIndexOf("/") + 1);
        // 规则1
        rule1.setFileId(fileName.replace(".", "-thumbnail."));
        rule1.setRule("imageView2/rq/30");
        ruleList.add(rule1);

        // // 规则2
        // PicOperations.Rule rule2 = new PicOperations.Rule();
        // rule2.setBucket(cosClientConfig.getBucket());
        // fileName = fileName.substring(0, fileName.lastIndexOf("."));
        // rule2.setFileId(fileName + "-compress.tpg");
        // rule2.setRule("imageMogr2/format/tpg");
        // ruleList.add(rule2);
        // 构造处理参数
        picOperations.setRules(ruleList);
        putObjectRequest.setPicOperations(picOperations);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 删除对象
     */
    public void deleteObject(String key) {
        cosClient.deleteObject(cosClientConfig.getBucket(), key);
    }
}
